package com.roin.learn.springsecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.roin.learn.springsecurity.common.exception.ApiException;
import com.roin.learn.springsecurity.entity.SysAdmin;
import com.roin.learn.springsecurity.entity.SysPermission;
import com.roin.learn.springsecurity.enums.ResultCode;
import com.roin.learn.springsecurity.mapper.SysAdminMapper;
import com.roin.learn.springsecurity.mapper.SysAdminRoleRelationMapper;
import com.roin.learn.springsecurity.model.AdminDetails;
import com.roin.learn.springsecurity.service.SysAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.roin.learn.springsecurity.util.JwtTokenUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统管理员用户表 服务实现类
 * </p>
 *
 * @author Roin
 * @since 2021-01-07
 */
@Service
@Log4j2
public class SysAdminServiceImpl extends ServiceImpl<SysAdminMapper, SysAdmin> implements SysAdminService {

    @Autowired
    SysAdminMapper sysAdminMapper;
    @Autowired
    SysAdminRoleRelationMapper sysAdminRoleRelationMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public SysAdmin getAdminByUsername(String username) {
        QueryWrapper<SysAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return sysAdminMapper.selectOne(queryWrapper);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysAdmin admin = getAdminByUsername(username);
        if (admin!=null){
            List<SysPermission> permissionList = sysAdminRoleRelationMapper.getPermissionListByAdminId(admin.getId());
            List<GrantedAuthority> authorityList = permissionList.stream()
                    .map(permission ->new SimpleGrantedAuthority(permission.getId()+":"+permission.getName()))
                    .collect(Collectors.toList());
            return new AdminDetails(admin,authorityList);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
            if(!passwordEncoder.matches(password,userDetails.getPassword())){
                throw new ApiException(ResultCode.USER_CREDENTIALS_ERROR);
            }
            if(!userDetails.isEnabled()){
                throw new ApiException(ResultCode.USER_ACCOUNT_DISABLE);
            }
            if (!userDetails.isAccountNonLocked()) {
                throw new ApiException(ResultCode.USER_ACCOUNT_LOCKED);
            }
            if (!userDetails.isCredentialsNonExpired()) {
                throw new ApiException(ResultCode.USER_CREDENTIALS_EXPIRED);
            }
            if (!userDetails.isAccountNonExpired()) {
                throw new ApiException(ResultCode.USER_ACCOUNT_EXPIRED);
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
            throw new ApiException(ResultCode.USER_CREDENTIALS_ERROR);
        }
        return token;
    }

    @Override
    public String refreshToken(String oldToken) {
        return jwtTokenUtil.refreshHeadToken(oldToken);
    }
}
